from trackerclientpylons.lib.base import *
from trackerclientpylons.model.result import *
import mimetypes
import gnome.ui
import gtk



class IndexController(BaseController):
    
    def __init__(self):
        BaseController.__init__(self)
    
    def icon(self):
		print "in icon"
		iconTheme = gtk.icon_theme_get_default()
		iconFactory = gnome.ui.ThumbnailFactory(gnome.ui.THUMBNAIL_SIZE_NORMAL)
		uri = 'file://' + request.params.get('uri', '')
		result, flags = gnome.ui.icon_lookup(iconTheme, iconFactory, uri)
		info = iconTheme.lookup_icon(result, 32, gtk.ICON_LOOKUP_NO_SVG)
		if info is None:
			return ""
		else:
			icon_name = info.get_filename()
		mime = mimetypes.guess_type(uri)[0]
		if not mime:
			mime = 'application/unknown'
		response.content_type__set(mime)
		f = open(icon_name, "rb", 0)
		def open_pause():
			segment = f.read(128)
			while segment != '':
				yield segment
				segment = f.read(128)
			f.close()
		return open_pause()
    
    def on_tracker_error(self, message):
        pass
    
    def detail(self):
       return render("/detail.mako")

    def tag(self):
        url = request.params.get('url', '')
        tag = [request.params.get('tag', '')]
        if tag != ['']:
            session['rs'].tagByUrl(url, tag)
            return "Tag Added!"
        else:
            return "Please enter a tag"
    
    def find(self):
        filter = request.params.get('filter', 'Files')
        query = Query(request.params['query'], filter, 0, 10, request.params.get('byTag', 'off') == 'on')
        rs = ResultSet(query)
        rs.search()
        session['rs'] = rs
        session.save()
        return render("/result.mako")
    
    
    def next(self):
        session['rs'].next()
        return render("/result.mako")
    
    
    def prev(self):
        session['rs'].prev()
        return render("/result.mako")
    
    
    def index(self):
        return render('/index.mako');
    
    def open(self):
        url = request.params.get('url', '')
        mime = mimetypes.guess_type(url)[0]
        if not mime:
        	mime = 'application/unknown'
        response.content_type__set(mime)
        f = open(url, "rb", 0)
        def open_pause():
            segment = f.read(128)
            while segment != '':
                yield segment
                
                segment = f.read(128)
            f.close()
        return open_pause()

   